const { execFileSync } = require('child_process')
const fs = require('fs-extra');
const path = require('path');
const { getJson, writeJson } = require('../lib/utils/util');
const dateFormat = require('dateformat');

class Git {
    constructor({ cwd, log }) {
        this.cwd = cwd;
        this.log = log;
    }

    command(cmd) {
        let msg = execFileSync('git', Array.isArray(cmd) ? cmd : cmd.split(' '), {cwd: this.reps}).toString('utf8');
        if(this.log){
            console.log(msg);
        }
        return msg;
    }
}

class Store {
    constructor() {
        this.git = new Git({cwd: __dirname, log: true});
    }

    getJsonFile (name, date) {
        date = date || dateFormat(new Date(), "yyyy_mm_dd");
        return path.join(__dirname, 'json', date, name + ".json");
    }

    addJson(name, json, date) {
        writeJson(this.getJsonFile(name, date), json);
        return this;
    }
    
    getJson(name, date) {
        return getJson(this.getJsonFile(name, date));
    }

    testJson(name, date){
        return fs.existsSync(this.getJsonFile(name, date));
    }

    ci(msg) {

        this.git.command('add .');

        this.git.command(`commit -m "${msg || '_'}"`);

        return this;
    }

    push() {
        this.git.command('push');
        return this;
    }
}

module.exports = new Store();
